﻿using Sx.Mall.WebContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Sx.Mall.Web.Filter
{
    public class SendMail 
    {
        public SendMail()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="tomail">对方的mail</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件类容</param>
        /// <returns></returns>
        public MailMessage MakeMail(string tomail, string title, string content)
        {
            MailMessage msg = new MailMessage();
            msg.To.Add(tomail);
            msg.From = new MailAddress(MailConfig.SMTPUser, MailConfig.DisplayName);
            msg.Subject = title;
            msg.Body = content;
            msg.IsBodyHtml = true;
            msg.SubjectEncoding = Encoding.GetEncoding("utf-8");
            msg.BodyEncoding = Encoding.GetEncoding("utf-8");

            return msg;
        }

        /// <summary>
        /// 获取配置文件中参数
        /// </summary>
        public SmtpClient SMTP
        {
            get
            {
                SmtpClient smtp = new SmtpClient(MailConfig.SMTPServer, MailConfig.SMTPPort);
                smtp.Credentials = new NetworkCredential(MailConfig.SMTPUser, MailConfig.SMTPPwd);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.EnableSsl = false;
                return smtp;
            }
        }

        public bool Send(MailMessage msg)
        {
            try
            {
                SmtpClient smtp = SMTP;
                smtp.Send(msg);
                return true;
            }
            catch (Exception error)
            {
                return false;
            }
        }
    }
}
